package com.heer.gymnasium.api.callback;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.api.CallManager;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.constants.ReturnCode;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.base.BaseBean;
import com.heer.gymnasium.constant.IMessage;
import com.heer.gymnasium.module.login.views.LoginActivity;

import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by JS01 on 2016/6/14.
 * 使用Retrofit2 Call异步请求时的回调
 */
public abstract class BaseCallback<T> implements Callback<T>, IMessage {

    private static final String TAG = "BaseCallback";

    @Override
    public void onResponse(Call<T> call, Response<T> response) {
        Log.d(TAG, "code:" + response.code());
        CallManager.remove(call);
        if (response.isSuccessful()) {
            if (response.code() == ReturnCode.SUCCESS && (response.body() instanceof ApiResponse) && (((ApiResponse) response.body()).getErrorcode() == ReturnCode.SUCCESS)) {
                onSuccess(call, response);
            } else if (response.code() == ReturnCode.SUCCESS) {
                if ((response.body() instanceof ApiResponse) && ((ApiResponse) response.body()).getErrorcode() == ReturnCode.TIME_OUT) {
                    onTokenTimeOut();
                } else if ((response.body() instanceof ApiResponse) && ((ApiResponse) response.body()).getErrorcode() == ReturnCode.PLUGIN_LIMIT_MESSAGE) {
                    onError(call, new Throwable(PLUGIN_LIMIT_MESSAGE));
                } else if (response.body() instanceof ApiResponse) {
                    onError(call, new Throwable(((ApiResponse) response.body()).getMsg()));
                } else {
                    onError(call, new Throwable());
                }
            } else {
                onError(call, new Throwable(response.message()));
            }
        } else {
            onError(call, new Throwable(response.message()));
        }
    }

    @Override
    public void onFailure(Call<T> call, Throwable t) {
        Log.d(TAG, "error:" + t.getLocalizedMessage());
        CallManager.remove(call);
        onError(call, t);
    }

    public abstract void onSuccess(Call<T> call, Response<T> response);

    public void onTokenTimeOut() {
        BaseActivity.timeout();
    }

    public void onError(Call<T> call, Throwable t) {
        BaseActivity.requestErrorToast(t.getMessage());
    }
}
